local UIBase = require("view.UIBase")
local BloodUI = class("BloodUI", UIBase)
local GameUtils = require("utils.GameUtils")
local Vector3 = require("utils.Vector3")
local Vector2 = require("utils.Vector2")
local UIUtil = require("utils.UIUtil")
local Color = require("utils.Color")

function BloodUI:ctor(actor)
    self._value = 0
    self._maxValue = 0
    self._actor = actor
    self._lastPos = Vector2.new(0, 0)
    local resource = {
        path = "Prefabs/UI",
        name = "BloodUI",
        canvas = 1
    }
    BloodUI.super.ctor(self, resource)
end

function BloodUI:awake()
end

function BloodUI:setElement(element)
    self._textElement.text = Lang.get("lang_element_" .. element)
    self._textElement.color = Color.getElementColor(element)
end

function BloodUI:setName(name)
    self._name = name
    if self._textName then
        self._textName.text = name
    end
end

function BloodUI:start()
    self:setName(self._name)
    self._btnSee.onClick:AddListener(handler(self, self._onBtnSeeClick))
    self._rect = self.gameObject:GetComponent(typeof(CS.UnityEngine.RectTransform))
    self._uiCamera = G_UIManager:getUICamera()
    self._mainCamera = UIUtil.getMainCamera()
    self._parentRect = self.transform.parent:GetComponent(typeof(CS.UnityEngine.RectTransform))
    self:updatePosition()
end

function BloodUI:update()
    self:updatePosition()
end

function BloodUI:updatePosition()
    local trans = self._actor.transform
    local screenPoint = self._mainCamera:WorldToScreenPoint(trans.position)
    if Vector3.equal(screenPoint, self._lastPos) then
        return
    end
    self._lastPos = screenPoint
    local screenPoint2 = Vector2.new(screenPoint.x, screenPoint.y)
    local outPos = G_UIManager:ScreenPointToLocalPointInRectangle(self._parentRect, screenPoint2, self._uiCamera)
    self._rect.localPosition = Vector3.new(outPos.x, outPos.y + 120, 0)
end

function BloodUI:setValue(value, maxValue)
    self._value = value
    self._maxValue = maxValue
    if self._fill then
        self._fill.fillAmount = value / maxValue
    end
end

function BloodUI:setVisible(visible)
    self.gameObject:SetsActive(visible)
end

function BloodUI:_onBtnSeeClick()
    G_SignalManager:dispatch(SignalConst.EVENT_SEE_FIGHT_ENTITY_ATTR, self._actor:getId())
end

return BloodUI
